<script>
/* 引入COS */
import COS from 'cos-js-sdk-v5';
/* 创建COS的实例 */
const cos = new COS({
  SecretId: 'AKIDEJFzav10kO2kMlxvfGjyBQWRCrQ0Vr3B',
  SecretKey: 'AHFyVu9HF3jZN86uY1OabY9oNqAXt7GF',
});

export default {
  name: "uploadAvatar",
  data() {
    return {
      progress: 0
    }
  },
  props: {
    /* 父组件传递过来的prop */
    value: {
      type: String,
      default: ''
    }
  },

  methods: {

    /* 覆盖默认的上传行为，可以自定义上传实现 */
    async handleRequest(result) {
      //  Bucket:填写自己的存储桶名称，必须字段
      //  Region:存储桶所在地域，必须字段
      //  Key:存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段
      //  Body:上传文件对象
      //  StorageClass: 'STANDARD'上传模式标准模式
      try {
        const response = await cos.putObject({
          Bucket: 'wbepng-1321002078', Region: 'ap-nanjing',
          Key: result.file.name, Body: result.file,
          StorageClass: 'STANDARD', onProgress: (progress) => {
            this.progress = Math.floor(progress.percent * 100)
          }
        })
        console.log(response)
        // 将值传递给父组件
        this.$emit('input', `https://${response.Location}`)
        this.$message.success('上传成功')
      } catch (e) {
        this.$message.error('上传失败')
      }
    },

    /* 头像上传之前的回调函数 */
    beforeAvatarUpload(file) {
      const isImg = file.type.indexOf('image') !== -1
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImg) this.$message.error('上传头像只能是图片!')
      if (!isLt2M) this.$message.error('上传头像图片大小不能超过 2MB!')
      return isImg && isLt2M;
    }
  }
}
</script>

<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="handleRequest">
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-progress :percentage="progress" v-if="progress"></el-progress>
  </div>
</template>
<style scoped lang="scss">
.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

::v-deep .el-progress-bar {
  width: 65% !important;
}

</style>
